package org.example.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.example.model.LoginUser;

import java.util.Date;

/**
 * @description: JWT关于token等设置
 * @author: 谢超
 * @date: 2023/08/12 21:02
 **/
@Slf4j
public class JWTUtil {

    /**
     * 主键
     */
    private static final String SUBJECT = "xdclass";

    /**
     * 加密密钥
     */
    private static final String SECRET = "xdclass.net168";

    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "dcloud-link";

    /**
     * token过期时间, 7天
     */
    private static final long EXPIRED = 1000 * 60 * 60 * 24 * 7;

    public static String geneJsonWebToken(LoginUser loginUser) {
        if (loginUser == null) {
            throw new NullPointerException("对象为空");
        }

        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", loginUser.getHeadImg())
                .claim("account_no", loginUser.getAccountNo())
                .claim("mail", loginUser.getMail())
                .claim("phone", loginUser.getPhone())
                .claim("auth", loginUser.getAuth())
                .setIssuedAt(new Date())  // 发布时间
                .setExpiration(new Date(CommonUtil.getCurrentTimestamp() + EXPIRED))  // 过期时间
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();// 设置签名

        token = TOKEN_PREFIX + token;
        return token;
    }

    /**
     * 解密token
     * @param token
     * @return
     */
    public static Claims checkJWT (String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
            return claims;
        } catch (Exception e) {
            log.warn("token解密失败:{}", e.getMessage());
            return null;
        }
    }
}
